<template>
  <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option
          v-for="item in employeesList"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="submit">确定</el-button>
      <el-button size="small">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployees } from '@/api/employees'
import { addDepartment, updateDepartment, departmentDaile } from '@/api/department'
export default {
  name: 'VueHrDeptDialog',
  props: {
    id: {
      type: String,
      required: true
    },
    // 接收是编辑还是添加的状态
    isedit: {
      type: Boolean,
      required: true
    },
    origenList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 自定义校验部门编码非重校验 includes(value) 是数组中包含了value 就返回true
    const validCode = (rule, value, callback) => {
      // console.log(value)
      let orcode = this.origenList.map(item => item.code)
      // console.log(orcode)
      // 如果是验证编辑状态，就要先排除自己，然后再拿到所有的部门名称
      if (this.isedit) {
        orcode = this.origenList.filter(item => item.id !== this.id).map(item => item.name)
        // console.log(orcode)
      }
      if (orcode.includes(value)) {
        callback(new Error(`部门编码：${value} 已存在`))
      }
      callback()
    }
    // 自定义校验部门名称非重校验 includes(value) 是数组中包含了value 就返回true
    const validName = (rule, value, callback) => {
      // console.log(value)
      // console.log(this.id)
      let orname = this.origenList.filter(item => item.pid === this.id).map(item => item.name)
      if (this.isedit) {
        // 先找到被编辑的部门
        const n = this.origenList.find(item => item.id === this.id)
        // console.log(n)
        const pid = n.pid
        orname = this.origenList.filter(item => item.pid === pid).filter(item => item.id !== this.id).map(item => item.name)
        // console.log(orname)
      }
      if (orname.includes(value)) {
        callback(new Error(`部门名称：${value}已存在`))
      } else {
        callback()
      }
      // console.log(orname)
    }
    return {
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 30, message: '请输入1-30个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请输入部门负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '请输入1-300个字符', trigger: 'blur' }

        ]
      },
      employeesList: [] // 负责人列表
    }
  },
  created() {
    // 调用部门负责人的请求
    this.loadEmployees()
    // 如果this.isedit 是true就说明是编辑状态，调用dodaile()函数，并把数据回显到表单
    if (this.isedit) {
      this.dodaile()
    }
  },
  methods: {
    // 重置表单
    resetForm() {
      this.$refs.deptForm.restFields()
    },
    submit() {
      // 兜底校验
      this.$refs.deptForm.validate((valit) => {
        // console.log(valit) // true 或 false
        if (valit) {
          this.isedit ? this.doedit() : this.hadd()
        }
      })
    },
    // 查询部门详情
    async dodaile() {
      // 如果是编辑状态就在created中调用
      const res = await departmentDaile(this.id)
      // console.log(res)
      if (res.code !== 10000) return this.$message.error(res.message)
      this.$message.success(res.message)

      this.form = res.data
    },
    // 编辑
    async doedit() {
      // console.log('编辑')
      // 发送编辑的请求
      const res = await updateDepartment(this.form)
      console.log(res)
      this.$emit('success')
    },
    async hadd() {
      // 添加子部门
      try {
        // 此处请求的参数id是从父组件传递过来的
        const res = await addDepartment({ ...this.form, pid: this.id })
        // console.log(this.id)
        // console.log(this.form)
        // console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 数据在子组件，渲染页面的函数在父组件，所以给父组件传递一个触发的事件
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },

    // 获取部门负责人信息
    async loadEmployees() {
      try {
        const res = await getEmployees()
        // console.log(res)
        this.employeesList = res.data
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
